from datetime import datetime, timedelta
from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from sqlalchemy import and_, func, desc, case
from app.models.treatment import TreatmentRecord, TreatmentTemplate
from app.models.user import User
from app.models.device import Device, DeviceLog
from app.extensions import db
from app.utils.decorators import handle_errors

dashboard_bp = Blueprint('dashboard', __name__, url_prefix='/api/dashboard')


@dashboard_bp.route('/stats', methods=['GET'])
@jwt_required()
@handle_errors
def get_dashboard_stats():
    """获取仪表板统计数据"""
    current_user_id = get_jwt_identity()
    
    # 基础统计
    total_users = User.query.count()
    # 根据治疗记录统计设备总数
    total_devices = db.session.query(func.count(func.distinct(TreatmentRecord.device_id))).scalar() or 0
    online_devices = Device.query.filter_by(status='online').count()
    today = datetime.now().date()
    today_treatments = TreatmentRecord.query.filter(
        func.date(TreatmentRecord.created_at) == today
    ).count()
    
    # 完成率统计
    total_treatments = TreatmentRecord.query.count()
    completed_treatments = TreatmentRecord.query.filter_by(status='completed').count()
    completion_rate = (completed_treatments / total_treatments * 100) if total_treatments > 0 else 0
    
    return jsonify({
        'totalUsers': total_users,
        'totalDevices': total_devices,  # 根据治疗记录统计的设备总数
        'onlineDevices': online_devices,
        'todayTreatments': today_treatments,
        'completionRate': round(completion_rate, 2),
        'totalTreatments': total_treatments,
        'completedTreatments': completed_treatments
    })


@dashboard_bp.route('/treatment-trends', methods=['GET'])
@jwt_required()
@handle_errors
def get_treatment_trends():
    """获取治疗趋势数据"""
    current_user_id = get_jwt_identity()
    
    # 获取天数参数，默认30天
    days = request.args.get('days', 30, type=int)
    end_date = datetime.now()
    start_date = end_date - timedelta(days=days)

    # 查询每日治疗数据
    trends = db.session.query(
        func.date(TreatmentRecord.created_at).label('date'),
        func.count(TreatmentRecord.id).label('total_treatments'),
        func.sum(case((TreatmentRecord.status == 'completed', 1), else_=0)).label('completed_treatments'),
        func.avg(TreatmentRecord.current_intensity).label('avg_intensity')
    ).filter(
        TreatmentRecord.created_at >= start_date,
        TreatmentRecord.created_at <= end_date
    ).group_by(
        func.date(TreatmentRecord.created_at)
    ).order_by(
        func.date(TreatmentRecord.created_at)
    ).all()
    
    # 格式化数据
    result = []
    for trend in trends:
        completion_rate = (trend.completed_treatments / trend.total_treatments * 100) if trend.total_treatments > 0 else 0
        result.append({
            'date': str(trend.date),
            'total_treatments': trend.total_treatments,
            'completed_treatments': int(trend.completed_treatments or 0),
            'completion_rate': round(float(completion_rate), 2),
            'avg_intensity': round(float(trend.avg_intensity or 0), 2)
        })
    
    return jsonify(result)


@dashboard_bp.route('/user-trends', methods=['GET'])
@jwt_required()
@handle_errors
def get_user_trends():
    """获取用户增长趋势"""
    current_user_id = get_jwt_identity()
    
    # 获取天数参数，默认30天
    days = request.args.get('days', 30, type=int)
    end_date = datetime.utcnow().date()
    start_date = end_date - timedelta(days=days)
    
    # 查询每日用户数据
    trends = db.session.query(
        func.date(User.created_at).label('date'),
        func.count(User.id).label('new_users')
    ).filter(
        User.created_at >= start_date,
        User.created_at <= end_date
    ).group_by(
        func.date(User.created_at)
    ).order_by(
        func.date(User.created_at)
    ).all()
    
    # 获取累计用户数
    cumulative_users = []
    total_users = 0
    for trend in trends:
        total_users += trend.new_users
        cumulative_users.append({
            'date': str(trend.date),
            'new_users': trend.new_users,
            'total_users': total_users
        })
    
    return jsonify(cumulative_users)


@dashboard_bp.route('/device-status', methods=['GET'])
@jwt_required()
@handle_errors
def get_device_status_distribution():
    """获取设备状态分布"""
    current_user_id = get_jwt_identity()
    
    # 设备状态统计
    status_stats = db.session.query(
        Device.status,
        func.count(Device.id).label('count')
    ).group_by(Device.status).all()
    
    result = [{'status': status, 'count': count} for status, count in status_stats]
    return jsonify(result)


@dashboard_bp.route('/treatment-modes', methods=['GET'])
@jwt_required()
@handle_errors
def get_treatment_mode_distribution():
    """获取治疗模式分布"""
    current_user_id = get_jwt_identity()
    
    # 获取天数参数，默认30天
    days = request.args.get('days', 30, type=int)
    end_date = datetime.utcnow()
    start_date = end_date - timedelta(days=days)
    
    # 治疗模式统计
    mode_stats = db.session.query(
        TreatmentRecord.treatment_mode,
        func.count(TreatmentRecord.id).label('count')
    ).filter(
        TreatmentRecord.created_at >= start_date,
        TreatmentRecord.created_at <= end_date
    ).group_by(TreatmentRecord.treatment_mode).all()
    
    result = [{'mode': mode, 'count': count} for mode, count in mode_stats]
    return jsonify(result)